package neu.tour.activity;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.lang.Math;

import neu.tour.R;
import neu.tour.support.HandlePic;
import neu.tour.support.InitSystemBar;
import neu.tour.support.SaveDataToFile;


public class EditActivity extends Activity {

    private ImageView imageView;//定义图片显示的容器
    private ImageView borderView;//老照片容器
    private LinearLayout borderButton;//显示轮廓按钮
    private LinearLayout redoButton;//重做按钮
    private LinearLayout shareButton;//分享按钮
    private Bitmap newPicBitmap;//刚拍完照的新图片
    private Bitmap oldPicBitmap;//老照片
    private Mat newMat;//新图片矩阵
    private Mat oldMat;//老图片矩阵
    private boolean isDraw = false;//是否进行绘制a
    private boolean isShowBorder = false;//是否显示边缘图
    private boolean flag = false;
    private float screenWidth;// 屏幕宽度
    private float showHeight;//屏幕宽度的4/3
    private int newPicWidth;
    private int newPicHeight;
    private int shifting;//偏移
    private int borderPicHeight;//边缘图的高
    private String savePath = "/AATour/edit/"; //编辑后的图片的存储路径
    private int mark[][];


    /**
     * 加载OpenCV必备函数
     */
    private BaseLoaderCallback  mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:{
                    Log.i("OpenCV", "Load success");
                } break;
                default:{
                    super.onManagerConnected(status);
                } break;
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        InitSystemBar.initSystemBar(this);
        setContentView(R.layout.activity_edit);

        if (!OpenCVLoader.initDebug()) {
            OpenCVLoader.initAsync(
                    OpenCVLoader.OPENCV_VERSION_3_1_0,
                    this, mLoaderCallback);
        } else {
            mLoaderCallback.onManagerConnected(
                    LoaderCallbackInterface.SUCCESS);
        }

        screenWidth  = getWindowManager().
                getDefaultDisplay().getWidth();
        showHeight = screenWidth/3*4;

        initImageView();//初始化图片
        initBorderButton();//初始化轮廓
        initRedoButton();//初始化重做
        initShareButton();//初始化分享
    }


    /**
     * 初始化图片
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initImageView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        // 获取新拍摄的照片
        String filename = bundle.getString("filename");//获取文件名
        int id = bundle.getInt("selectedImgId");//获取id
        String path = Environment.getExternalStorageDirectory()
                 + "/AATour/camera/" + filename;
        File mFile = new File(path);
        if (mFile.exists()) {
            newPicBitmap = BitmapFactory.decodeFile(path);
            imageView = (ImageView) findViewById(R.id.imageView);
            HandlePic h = new HandlePic();// 放缩新照片
            Bitmap newPicBitmap_ratio = h.changeBitmapSize(
                    newPicBitmap, screenWidth, showHeight);
            newPicBitmap = newPicBitmap_ratio;
            imageView.setImageBitmap(newPicBitmap);
            newPicWidth = newPicBitmap.getWidth();
            newPicHeight = newPicBitmap.getHeight();
        } else {
            Toast.makeText(getApplicationContext(),
                    "读取照片失败", Toast.LENGTH_SHORT).show();
            finish();
        }
        Resources r = getResources();  //获得Resources实例
        Bitmap selectedImg = BitmapFactory.decodeResource(r, id);
        // 保持老照片长宽比的新高度
        float newHeight = (screenWidth/(float)selectedImg.getWidth())
                * selectedImg.getHeight();
        HandlePic h = new HandlePic();// 放缩bitmap
        oldPicBitmap = h.changeBitmapSize(selectedImg, screenWidth, newHeight);
        Bitmap oldPicBoder = h.getBorder(oldPicBitmap);
        borderView = (ImageView)findViewById(R.id.borderView);
        borderView.setImageBitmap(oldPicBoder);
        newPicBitmap.setHasAlpha(true);
        Utils.bitmapToMat(newPicBitmap, newMat = new Mat());
        Utils.bitmapToMat(oldPicBitmap, oldMat = new Mat());
        mark = new int[oldMat.width()][oldMat.height()];
        for(int i=0;i<oldMat.width();i++){
            for(int j=0;j<oldMat.height();j++){
                mark[i][j] = 0;
            }
        }
        imageView.setOnTouchListener(touchListener);
    }


    /**
     * Imageiew的触摸事件
     */
    ImageView.OnTouchListener touchListener = new ImageView.OnTouchListener(){
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch(motionEvent.getAction()){
                case MotionEvent.ACTION_MOVE:
                    if(isDraw){
                        shifting = borderView.getTop() - imageView.getTop();
                        borderPicHeight = borderView.getHeight();
                        int x = (int)motionEvent.getX();
                        int y = (int)motionEvent.getY();
                        y = y-shifting;
                        if(x<=0 || y<=0 || x>=newPicWidth || y>=borderPicHeight){
                            break;
                        } else {
                            onEdit(x, y);
                        }
                    }
                case MotionEvent.ACTION_DOWN:
                    isDraw = true;
                    break;
                case MotionEvent.ACTION_UP:
                    isDraw = false;
                    break;
            }
            return true;
        }
    };


    /**
     * 编辑（即擦除）
     * 先用矩形，再考虑圆形
     */
    public void onEdit(int x, int y) {

        int m = 60;
        if(x-m<0||y-m<0){
            m = Math.min(x, y);
        }else if(x+m>newPicWidth||y+m>borderPicHeight){
            m = Math.min(newPicWidth-x, borderPicHeight-y);
        }

        //矩形
//        Rect r1 = new Rect(x-m, y-m+shifting, m, m); //构造矩形ROI区域
//        Rect r2 = new Rect(x-m, y-m, m, m);
//        Mat newROI = newMat.submat(r1);
//        Mat oldROI = oldMat.submat(r2);
//        Core.addWeighted(newROI, 0.0, oldROI, 1.0, 0., newROI);

        //圆形
        double r = (float)m / 5 * 4;
        for(int i = x - m; i < x + m; i++){
            for(int j = y - m; j < y + m; j++){
                if(i<=0 || i>=screenWidth || j<=0 || j>=borderPicHeight) break;
                double distance = Math.sqrt(Math.pow((x-i),2)+Math.pow((y-j),2));
                if(distance <= r){
                    if(mark[i][j]<1){
                        mark[i][j] += 1;
                        newPicBitmap.setPixel(i,j+shifting,oldPicBitmap.getPixel(i,j));
                    }
                }else if(distance>r && distance<=m){
                    if(mark[i][j] < 1){
                        int k = newPicBitmap.getPixel(i,j+shifting);
                        String k_0x = Integer.toHexString(k);
                        String new_k_0x = "e0" + k_0x.substring(2,8);
                        int newpixel = Color.parseColor("#"+new_k_0x);
                        newPicBitmap.setPixel(i,j+shifting, newpixel);
                    }
                }
            }
        }
        imageView.setImageBitmap(newPicBitmap); //让imageView显示修改后的图片
    }


    /**
     * 初始化轮廓
     */
    private void initBorderButton() {
        borderButton = (LinearLayout)findViewById(R.id.border);
        borderButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                isShowBorder = !isShowBorder;
                if(isShowBorder){
                    borderView.setVisibility(View.VISIBLE);
                } else {
                    borderView.setVisibility(View.INVISIBLE);
                }
            }
        });
    }


    /**
     * 初始化重做
     */
    private void initRedoButton() {
        redoButton = (LinearLayout)findViewById(R.id.redo);
        redoButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                initImageView();//初始化图片
            }
        });
    }


    /**
     * 初始化分享
     */
    private void initShareButton() {
        shareButton = (LinearLayout)findViewById(R.id.share);
        shareButton.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                //先把编辑后的图片存到SD
                SaveDataToFile s = new SaveDataToFile(savePath, 0);
                try {
                    s.saveToSDCard(newPicBitmap);
                }catch (IOException e) {
                    e.printStackTrace();
                }
                String imagePath = Environment.getExternalStorageDirectory()
                        + "/AATour/edit/" + s.getFilename();
                //由文件得到uri
                Uri imageUri = Uri.fromFile(new File(imagePath));
                Intent shareButtonIntent = new Intent();
                shareButtonIntent.setAction(Intent.ACTION_SEND);
                shareButtonIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                shareButtonIntent.setType("image/*");
                startActivity(Intent.createChooser(shareButtonIntent, "分享到"));
            }
        });
    }
}
